package _interview100;

/**
 * 200. 岛屿数量
 */
public class No200 {
    private char[][] grid;

    public int numIslands(char[][] grid) {
        this.grid = grid;
        int ans = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    ans++;
                    dfs(i, j);
                }
            }
        }
        return ans;
    }

    private void dfs(int i, int j) {
        if (!isValid(i, j) || grid[i][j] != '1') return;

        grid[i][j] = '2';
        dfs(i - 1, j);
        dfs(i + 1, j);
        dfs(i, j - 1);
        dfs(i, j + 1);
    }

    private boolean isValid(int i, int j) {
        return i >= 0 && j >= 0 && i < grid.length && j < grid[0].length;
    }
}
